package com.igroupes.ovineherd.model.attribute.id;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.igroupes.ovineherd.dto.response.Meta;
import com.igroupes.ovineherd.entity.DataModelAttributeEntity;
import com.igroupes.ovineherd.enums.BooleanKey;
import com.igroupes.ovineherd.model.IParentModelData;
import com.igroupes.ovineherd.model.Style.Group;
import com.igroupes.ovineherd.model.Style.NumberStyle;
import com.igroupes.ovineherd.model.Style.RadioStyle;
import com.igroupes.ovineherd.model.Style.TextStyle;
import com.igroupes.ovineherd.model.attribute.BasicAttribute;
import com.igroupes.ovineherd.model.dto.FieldApiResponse;
import com.igroupes.ovineherd.model.enums.FormKey;
import com.igroupes.ovineherd.query.FieldQuery;
import com.igroupes.ovineherd.query.ModelDataJsonAttributeQuery;
import com.igroupes.ovineherd.service.SequenceService;
import com.igroupes.ovineherd.util.DateUtils;
import com.igroupes.ovineherd.util.SpringPropertyUtils;
import com.igroupes.ovineherd.util.SpringUtil;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

import java.util.ArrayList;
import java.util.List;

/**
 * 流水号
 */
@EqualsAndHashCode(callSuper = true)
@Data
@ToString(callSuper = true)
public class IdAttribute extends BasicAttribute {
    public static final Integer MAX_PREFIX_LENGTH = 20; //前缀
    public static final Integer LENGTH = 1000;
    public static final String PREFIXCHAR_LABEL = "前置字符";
    public static final String PREFIXCHAR_DESC = "流水号前面添加字符值，最多"+MAX_PREFIX_LENGTH+"位";
    public static final String DATE_LABEL = "日期格式";
    public static final String DATE_DESC = "生成取当前时间格式拼接，如2020-10-10";
    public static final String AUTO_LABEL = "自增序号位数";
    public static final String AUTO_DESC = "自增位数，不足使用0填充，如4位：数字加入为1，生成为001";

    private TextStyle prefixChar;
    private RadioStyle dateRadio;
    private NumberStyle autoNumber;

    public IdAttribute() {
        super();
        this.required = null;
        this.prefixChar = new TextStyle(PREFIXCHAR_LABEL, "",false, IdAttribute.MAX_PREFIX_LENGTH,PREFIXCHAR_DESC);
        this.dateRadio = new RadioStyle(DATE_LABEL, "无", getGroups(), DATE_DESC);
        this.autoNumber = new NumberStyle( AUTO_LABEL, 5, false,AUTO_DESC);
    }
    private List<Group> getGroups(){
        List<Group> groups = new ArrayList<>();
        groups.add(new Group("无", "无",false));
        groups.add(new Group("年", "年",false));
        groups.add(new Group("年月", "年月",false));
        groups.add(new Group("年月日", "年月日",false));
        return groups;
    }

    public Boolean verifyField(IdAttribute idAttribute) {
        super.verifyField(idAttribute);
        new TextStyle().verify(idAttribute.getPrefixChar());
        new RadioStyle().verify(idAttribute.getDateRadio());
        new NumberStyle().verify(idAttribute.getAutoNumber());
        return true;
    }
    public Boolean verifyFieldV2(IdAttribute basic) {
        super.verifyFieldV2(basic);
        new TextStyle().verify( new TextStyle(PREFIXCHAR_LABEL, basic.getPrefixChar().getValue(),false, IdAttribute.MAX_PREFIX_LENGTH,PREFIXCHAR_DESC));
        new RadioStyle().verify(new RadioStyle(DATE_LABEL, basic.getDateRadio().getValue(), getGroups(), DATE_DESC));
        new NumberStyle().verify(new NumberStyle( AUTO_LABEL, basic.getAutoNumber().getValue(), false,AUTO_DESC));
        return true;
    }
    private void addSeq(String tableName, String key, int length){
        SpringUtil.getBean(SequenceService.class).addSequenceRecord(SpringPropertyUtils.modelTable() +"-"+tableName+"-"+key, length);
    }
    private Long getSeq(String tableName, String key){
        return SpringUtil.getBean(SequenceService.class).nextValue(SpringPropertyUtils.modelTable()+"-"+tableName+"-"+key);
    }

    @Override
    public  List<FieldQuery>  sqlField(IParentModelData parentModelData, DataModelAttributeEntity dataModelAttributeEntityOld) {
        IdAttribute idAttribute = (IdAttribute) parentModelData.getAttributes();
        List<FieldQuery> fieldQueries = super.sqlField(parentModelData,dataModelAttributeEntityOld);
        FieldQuery fieldQuery = fieldQueries.get(0);
        fieldQuery.setLength(LENGTH);

        DataModelAttributeEntity dataModelAttributeEntity = fieldQuery.getDataModelAttributeEntity();
        JSONObject jsonObject = dataModelAttributeEntity.getJson();
        jsonObject.set("prefixChar",Convert.toStr(idAttribute.getPrefixChar().getValue()));
        jsonObject.set("dateRadio", Convert.toStr(idAttribute.getDateRadio().getValue()));
        jsonObject.set("autoNumber",Convert.toInt(idAttribute.getAutoNumber().getValue()));
        jsonObject.set("tableName", parentModelData.getTableName());
        dataModelAttributeEntity.setJson(jsonObject);
        fieldQuery.setDataModelAttributeEntity(dataModelAttributeEntity);
        fieldQueries.set(0,fieldQuery);
        addSeq(parentModelData.getTableName(),fieldQuery.getFieldName(), Convert.toInt(idAttribute.getAutoNumber().getValue()));
        return fieldQueries;
    }

    @Override
    public JSONObject getAttribute(ModelDataJsonAttributeQuery modelDataJsonAttributeQuery) {
        JSONObject jsonObject = super.getAttribute(modelDataJsonAttributeQuery);
        jsonObject.set("required", null);
        jsonObject.set("prefixChar", new TextStyle(PREFIXCHAR_LABEL,  modelDataJsonAttributeQuery.getJson().get("prefixChar"),
                false, IdAttribute.MAX_PREFIX_LENGTH,PREFIXCHAR_DESC));
        jsonObject.set("dateRadio",new RadioStyle( DATE_LABEL, modelDataJsonAttributeQuery.getJson().get("dateRadio"), getGroups(), DATE_DESC));
        jsonObject.set("autoNumber",new NumberStyle( AUTO_LABEL, modelDataJsonAttributeQuery.getJson().get("autoNumber"), false,AUTO_DESC));
        return jsonObject;
    }

    @Override
    public List<FieldApiResponse> verifyRequestData(DataModelAttributeEntity modelAttributeEntity, Object value) {

        super.verifyRequestData(modelAttributeEntity, value);
        List<FieldApiResponse> fieldApiResponses = new ArrayList<>();
        if(value == null){
            return fieldApiResponses;
        }
        FieldApiResponse fieldDescribe = new FieldApiResponse();
        fieldDescribe.setDbName(modelAttributeEntity.getDbName());
        StringBuilder idValue = new StringBuilder();
        JSONObject jsonObject = modelAttributeEntity.getJson();
        if(ObjectUtil.isNotNull(jsonObject.get("prefixChar"))){
            String prefixChar = jsonObject.get("prefixChar").toString();
            if(!StringUtils.isBlank(prefixChar)){
                idValue.append(prefixChar);
            }
        }
        if(ObjectUtil.isNotNull(jsonObject.get("dateRadio"))){
            String dateRadio = jsonObject.get("dateRadio").toString();
            if(getDateRadioValue(dateRadio) != null){
                idValue.append(getDateRadioValue(dateRadio) );
            }
        }
        if(ObjectUtil.isNotNull(jsonObject.get("tableName"))){
            idValue.append(getSeq(Convert.toStr(jsonObject.get("tableName")),modelAttributeEntity.getDbName()));
        }
        fieldDescribe.setValue(idValue.toString());
        fieldApiResponses.add(fieldDescribe);
        return fieldApiResponses;
    }
//
//    private static String getNumberLength(long number, Integer autoNumber){
//        StringBuilder st = new StringBuilder();
//        Integer numberLength = (new Long(number)).toString().length();
//        if(autoNumber > numberLength){
//           return Convert.toStr(number).substring(autoNumber-3, autoNumber);
//        }
//        for (int i = 0; i< (autoNumber - numberLength); i++){
//            st.append("0");
//        }
//        st.append(number);
//        return st.toString();
//    }
    private static String getDateRadioValue(String date){
        if("无".equals(date)){
            return null;
        }else if("年".equals(date)){
            return DateUtils.getDate("yyyy");
        }else if("年月".equals(date)){
            return DateUtils.getDate("yyyy-MM");
        }else if("年月日".equals(date)){
            return DateUtils.getDate(DateUtils.DATE_FORMAT);
        }
        return null;
    }
    @Override
    public JSONObject getAttributeStyle(ModelDataJsonAttributeQuery dataModelAttributeEntity) {

        return new JSONObject(new TextStyle(
                dataModelAttributeEntity.getName(),"",
                dataModelAttributeEntity.getIsNull().equals(BooleanKey.TRUE.getCode()), "",true,
                dataModelAttributeEntity.getName()+"根据规则自动生成"
        ), false);
    }
    @Override
    public Meta getMeta(ModelDataJsonAttributeQuery dataModelAttributeEntity){
        return new Meta(FormKey.TEXT.getCode(), true, true, true);
    }
}
